<template>
  <div class="admin-orders">
    <div class="header-section">
      <h2>订单管理</h2>
      <p>管理员负责订单监控、审核异常订单、处理退款申请等系统级管理功能</p>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ stats.totalOrders }}</div>
              <div class="stat-label">总订单数</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ stats.totalRevenue }}</div>
              <div class="stat-label">总营收(元)</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ stats.pendingRefunds }}</div>
              <div class="stat-label">待处理退款</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ stats.todayOrders }}</div>
              <div class="stat-label">今日订单</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-section">
      <el-card>
        <el-form :model="searchForm" inline>
          <el-form-item label="订单号">
            <el-input v-model="searchForm.orderSn" placeholder="请输入订单号" clearable />
          </el-form-item>
          <el-form-item label="用户ID">
            <el-input v-model="searchForm.userId" placeholder="请输入用户ID" clearable />
          </el-form-item>
          <el-form-item label="订单状态">
            <el-select v-model="searchForm.status" placeholder="全部状态" clearable>
              <el-option label="待付款" value="UNPAID" />
              <el-option label="已付款" value="PAID" />
              <el-option label="已发货" value="SHIPPED" />
              <el-option label="已完成" value="COMPLETED" />
              <el-option label="已取消" value="CANCELLED" />
              <el-option label="退款中" value="REFUNDING" />
              <el-option label="已退款" value="REFUNDED" />
            </el-select>
          </el-form-item>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 订单列表 -->
    <div class="table-section">
      <el-card>
        <el-table
          :data="orderList"
          v-loading="loading"
          stripe
          style="width: 100%"
        >
          <el-table-column prop="orderId" label="订单ID" width="80" />
          <el-table-column prop="orderSn" label="订单号" width="180" />
          <el-table-column prop="userId" label="用户ID" width="100" />
          <el-table-column prop="totalAmount" label="订单金额" width="120">
            <template #default="{ row }">
              <span class="price">¥{{ row.totalAmount }}</span>
            </template>
          </el-table-column>
          <el-table-column label="订单状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="160">
            <template #default="{ row }">
              {{ formatDate(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="payTime" label="支付时间" width="160">
            <template #default="{ row }">
              {{ formatDate(row.payTime) }}
            </template>
          </el-table-column>
          <el-table-column label="管理员操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-dropdown @command="handleCommand" trigger="click">
                <el-button type="primary" size="small">
                  操作<el-icon class="el-icon--right"><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item :command="{ action: 'detail', row }">
                      <el-icon><View /></el-icon>查看详情
                    </el-dropdown-item>
                    <el-dropdown-item 
                      v-if="row.status === 'UNPAID'"
                      :command="{ action: 'cancel', row }"
                    >
                      <el-icon><Close /></el-icon>强制取消
                    </el-dropdown-item>
                    <el-dropdown-item 
                      v-if="row.status === 'PAID' || row.status === 'SHIPPED'"
                      :command="{ action: 'refund', row }"
                    >
                      <el-icon><Money /></el-icon>处理退款
                    </el-dropdown-item>
                    <el-dropdown-item 
                      v-if="row.status === 'CANCELLED' || row.status === 'COMPLETED' || row.status === 'REFUNDED'"
                      :command="{ action: 'delete', row }"
                      divided
                    >
                      <el-icon><Delete /></el-icon>删除订单
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-if="orderDetail" class="order-detail">
        <!-- 订单基本信息 -->
        <el-descriptions title="订单信息" :column="2" border>
          <el-descriptions-item label="订单号">{{ orderDetail.order.orderSn }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusType(orderDetail.order.status)">
              {{ getStatusText(orderDetail.order.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="订单金额">¥{{ orderDetail.order.totalAmount }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(orderDetail.order.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="支付时间" v-if="orderDetail.order.payTime">
            {{ formatDate(orderDetail.order.payTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="备注" v-if="orderDetail.order.remark">{{ orderDetail.order.remark }}</el-descriptions-item>
        </el-descriptions>

        <!-- 收货信息 -->
        <el-descriptions title="收货信息" :column="2" border style="margin-top: 20px;">
          <el-descriptions-item label="收货人">{{ orderDetail.receiverName }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ orderDetail.receiverPhone }}</el-descriptions-item>
          <el-descriptions-item label="收货地址" :span="2">{{ orderDetail.shippingAddress }}</el-descriptions-item>
        </el-descriptions>

        <!-- 商品信息 -->
        <div style="margin-top: 20px;">
          <h4>商品信息</h4>
          <el-table :data="orderDetail.items" border>
            <el-table-column prop="productName" label="商品名称" />
            <el-table-column prop="productPrice" label="单价" width="120">
              <template #default="{ row }">
                ¥{{ row.productPrice }}
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="80" />
            <el-table-column label="小计" width="120">
              <template #default="{ row }">
                ¥{{ (row.productPrice * row.quantity).toFixed(2) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>

    <!-- 退款处理对话框 -->
    <el-dialog
      v-model="refundDialogVisible"
      title="退款处理"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="refundForm" label-width="100px">
        <el-form-item label="退款金额">
          <el-input v-model="refundForm.amount" type="number" placeholder="请输入退款金额">
            <template #prepend>¥</template>
          </el-input>
        </el-form-item>
        <el-form-item label="退款原因">
          <el-select v-model="refundForm.reason" placeholder="请选择退款原因">
            <el-option label="商品质量问题" value="QUALITY_ISSUE" />
            <el-option label="商品与描述不符" value="DESCRIPTION_MISMATCH" />
            <el-option label="物流问题" value="LOGISTICS_ISSUE" />
            <el-option label="客户取消" value="CUSTOMER_CANCELLATION" />
            <el-option label="其他原因" value="OTHER" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注说明">
          <el-input
            v-model="refundForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入退款备注说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="refundDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmRefund">确认退款</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown, View, Close, Money, Delete } from '@element-plus/icons-vue'
import request from '@/utils/request'

// 响应式数据
const loading = ref(false)
const orderList = ref([])
const orderDetail = ref(null)
const detailDialogVisible = ref(false)
const refundDialogVisible = ref(false)
const currentOrder = ref(null)

// 统计数据
const stats = ref({
  totalOrders: 0,
  totalRevenue: 0,
  pendingRefunds: 0,
  todayOrders: 0
})

// 搜索表单
const searchForm = reactive({
  orderSn: '',
  userId: '',
  status: '',
  dateRange: []
})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 退款表单
const refundForm = reactive({
  amount: '',
  reason: '',
  remark: ''
})

// 获取订单列表
const fetchOrderList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.startDate = searchForm.dateRange[0]
      params.endDate = searchForm.dateRange[1]
    }
    
    const response = await request.get('/api/admin/orders', { params })
    if (response.success) {
      orderList.value = response.data.records || []
      pagination.total = response.data.total || 0
    } else {
      ElMessage.error('获取订单列表失败: ' + response.message)
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 获取统计数据
const fetchStats = async () => {
  try {
    const response = await request.get('/api/admin/orders/stats')
    if (response.success) {
      stats.value = response.data
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchOrderList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    orderSn: '',
    userId: '',
    status: '',
    dateRange: []
  })
  pagination.page = 1
  fetchOrderList()
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.page = 1
  fetchOrderList()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  fetchOrderList()
}

// 操作处理
const handleCommand = ({ action, row }) => {
  switch (action) {
    case 'detail':
      showOrderDetail(row)
      break
    case 'cancel':
      handleCancelOrder(row)
      break
    case 'refund':
      showRefundDialog(row)
      break
    case 'delete':
      handleDeleteOrder(row)
      break
  }
}

// 查看订单详情
const showOrderDetail = async (order) => {
  try {
    const response = await request.get(`/api/admin/orders/${order.orderId}/detail`)
    if (response.success) {
      orderDetail.value = response.data
      detailDialogVisible.value = true
    } else {
      ElMessage.error('获取订单详情失败: ' + response.message)
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败: ' + error.message)
  }
}

// 强制取消订单
const handleCancelOrder = async (order) => {
  try {
    await ElMessageBox.confirm(
      `确定要强制取消订单 ${order.orderSn} 吗？此操作不可撤销。`,
      '确认取消',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await request.put(`/api/admin/orders/${order.orderId}/cancel`)
    if (response.success) {
      ElMessage.success('订单已强制取消')
      fetchOrderList()
      fetchStats()
    } else {
      ElMessage.error('取消订单失败: ' + response.message)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error('取消订单失败: ' + error.message)
    }
  }
}

// 显示退款对话框
const showRefundDialog = (order) => {
  currentOrder.value = order
  refundForm.amount = order.totalAmount
  refundForm.reason = ''
  refundForm.remark = ''
  refundDialogVisible.value = true
}

// 确认退款
const confirmRefund = async () => {
  if (!refundForm.amount || !refundForm.reason) {
    ElMessage.warning('请填写完整的退款信息')
    return
  }
  
  try {
    const response = await request.post(`/api/admin/orders/${currentOrder.value.orderId}/refund`, refundForm)
    if (response.success) {
      ElMessage.success('退款处理成功')
      refundDialogVisible.value = false
      fetchOrderList()
      fetchStats()
    } else {
      ElMessage.error('退款处理失败: ' + response.message)
    }
  } catch (error) {
    console.error('退款处理失败:', error)
    ElMessage.error('退款处理失败: ' + error.message)
  }
}

// 删除订单
const handleDeleteOrder = async (order) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除订单 ${order.orderSn} 吗？此操作不可撤销。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await request.delete(`/api/admin/orders/${order.orderId}`)
    if (response.success) {
      ElMessage.success('订单已删除')
      fetchOrderList()
      fetchStats()
    } else {
      ElMessage.error('删除订单失败: ' + response.message)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除订单失败:', error)
      ElMessage.error('删除订单失败: ' + error.message)
    }
  }
}

// 状态相关方法
const getStatusType = (status) => {
  const statusMap = {
    'UNPAID': 'warning',
    'PAID': 'primary',
    'SHIPPED': 'info',
    'COMPLETED': 'success',
    'CANCELLED': 'danger',
    'REFUNDING': 'warning',
    'REFUNDED': 'info'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    'UNPAID': '待付款',
    'PAID': '已付款',
    'SHIPPED': '已发货',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消',
    'REFUNDING': '退款中',
    'REFUNDED': '已退款'
  }
  return statusMap[status] || status
}

const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN')
}

// 初始化
onMounted(() => {
  fetchOrderList()
  fetchStats()
})
</script>

<style scoped>
.admin-orders {
  padding: 20px;
}

.header-section {
  margin-bottom: 20px;
}

.header-section h2 {
  margin: 0 0 10px 0;
  color: #303133;
}

.header-section p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.stats-section {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
}

.stat-content {
  padding: 10px;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.search-section {
  margin-bottom: 20px;
}

.table-section {
  margin-bottom: 20px;
}

.pagination-section {
  margin-top: 20px;
  text-align: right;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

.order-detail {
  max-height: 600px;
  overflow-y: auto;
}

:deep(.el-descriptions__label) {
  font-weight: bold;
}
</style> 